<template>
  <view class="" style="padding-bottom: 120px;">
    <u-navbar v-if="!$isWeixin()" :title="title"></u-navbar>

    <view class="card-grid" v-if="type != 'add'">
      <view @click="pageJump(item)" class="card-item" v-for="(item, index) in functionList" :key="index">
        <u-avatar :size="100" :src="item.PhotoUrl"></u-avatar>
        <text class="label">{{ item.Name }}</text>
      </view>

      <view v-if="showShop" @click="goToShop" class="card-item">
        <u-avatar :size="100" src="../../static/images/home/item-15.png"></u-avatar>
        <text class="label">品宣物料申请</text>
      </view>
    </view>

    <checkbox-group @change="groupChange" v-else>
      <u-grid :border="true">
        <u-grid-item class="" v-for="(item, index) in functionList" :key="index">
          <label class="grid-item">
            <view class="u-flex-col u-col-center">
              <u-image :src="item.PhotoUrl" :width="80" :height="80"></u-image>
              <text class="grid-text u-line-1">{{ item.Name }}</text>
            </view>
            <checkbox
              style="transform:scale(0.7)"
              :checked="selectedFunctionList.includes(item.Id + '')"
              :value="item.Id + ''"
              :id="'checkbox_' + item.Id"
              :name="item.Id"
            ></checkbox>
          </label>
        </u-grid-item>
      </u-grid>
    </checkbox-group>

    <view v-if="type == 'add'" class="bottom-btn">
      <u-button @click="onClick" type="warning" style="margin: 0 16px; margin-top: 20px;">保存</u-button>
    </view>

    <u-modal
      :title="modalTitle"
      width="90%"
      :showLoading="false"
      :mask-close-able="true"
      v-model="showApplyModal"
      cancel-text="取消"
      :show-cancel-button="true"
      @confirm="toApplyPage"
      :async-close="true"
      confirm-text="确定"
      :negative-top="100"
    >
      <!-- <apply-search ref="applySearch" :storeRequired="storeRequired" :showDouble="showApplyDouble" :showStore="showApplyStore"></apply-search> -->
      <u-form label-position="top" :label-width="200" style="padding: 0rpx 40rpx;">
        <u-form-item label="" v-if="showDesignApplyTypeRadio">
          <u-radio-group v-model="designApplyType">
            <!-- <u-radio name="1">渠道平面设计</u-radio> -->
            <u-radio name="3">店内&展会平面设计</u-radio>
            <u-radio name="5">渠道其他画面设计</u-radio>
            <u-radio name="4">总部设计申请</u-radio>
            <!--           <u-radio name="6">旗舰店专卖店设计申请</u-radio>
            <u-radio name="7">非旗舰店专卖店设计申请</u-radio> -->
            <u-radio name="6">门店展陈设计</u-radio>
          </u-radio-group>
        </u-form-item>

        <block v-if="designApplyType != 4">
          <u-form-item label="一级经销商" required>
            <u-input
              :value="FirstDealer && FirstDealer.label"
              inputAlign="left"
              type="select"
              :selectOpen="showFirstDealerPicker"
              @tap="showFirstDealerPicker = true"
            ></u-input>
          </u-form-item>
          <u-form-item v-if="showApplyDouble || showApplyStore" label="二级经销商">
            <u-input
              :value="DoubleDealer && DoubleDealer.label"
              inputAlign="left"
              type="select"
              :selectOpen="showDoubleDealerPicker"
              @tap="showDoubleDealerPicker = true"
            ></u-input>
          </u-form-item>
          <u-form-item v-if="showApplyStore" label="门店" :required="storeRequired">
            <u-input
              :value="StoreDealer && StoreDealer.label"
              inputAlign="left"
              type="select"
              :selectOpen="showStoreDealerPicker"
              @tap="showStoreDealerPicker = true"
            ></u-input>
          </u-form-item>
        </block>
      </u-form>
    </u-modal>

    <u-select
      @confirm="onPickerChange($event, 1)"
      :default-value="[FirstDealerIndex]"
      v-model="showFirstDealerPicker"
      :list="FirstDealerList"
      label-name="Value"
      value-name="Key"
      safe-area-inset-bottom
    ></u-select>
    <u-select
      v-if="showApplyDouble || showApplyStore"
      @confirm="onPickerChange($event, 2)"
      :default-value="[DoubleDealerIndex]"
      v-model="showDoubleDealerPicker"
      :list="DoubleDealerList"
      label-name="Value"
      value-name="Key"
      safe-area-inset-bottom
    ></u-select>
    <u-select
      v-if="showApplyStore"
      @confirm="onPickerChange($event, 3)"
      :default-value="[StoreDealerIndex]"
      v-model="showStoreDealerPicker"
      :list="StoreDealerList"
      label-name="Value"
      value-name="Key"
      safe-area-inset-bottom
    ></u-select>
  </view>
</template>

<script>
import { pageJumpMixin } from '../../common/pageJump.mixin.js';
export default {
  mixins: [pageJumpMixin],
  data() {
    return {
      functionList: [],
      selectedFunctionList: [],
      level: '',
      parentId: '',
      title: '',
      type: '',

      showApplyModal: false,
      showApplyDouble: true,
      showApplyStore: true,
      applyType: '',

      showFirstDealerPicker: false,
      showDoubleDealerPicker: false,
      showStoreDealerPicker: false,

      FirstDealerList: [],
      FirstDealerIndex: -1,
      FirstDealer: {},

      DoubleDealerList: [],
      DoubleDealerIndex: -1,
      DoubleDealer: {},

      StoreDealerList: [],
      StoreDealerIndex: -1,
      StoreDealer: {},
      storeRequired: true,

      modalTitle: 'title',

      showShop: false,
      shopUrl: '',

      designApplyType: 1,
      showDesignApplyTypeRadio: false,

      showInformationChange: false,

      params: {
        FirstDealerId: null,
        DoubleDealerId: null,
        StoreDealerId: null,

        ApplyForType: 1
      }
    };
  },

  onLoad(options) {
    console.log(options);
    if (options.level) {
      this.level = options.level;
    }
    if (options.parentId) {
      this.parentId = options.parentId;

      if (this.parentId == 4) {
        this.loadUrl();
      }
    }
    if (options.title) {
      this.title = options.title;
    }
    if (options.type) {
      this.type = options.type;
    }
    if (options.commonFunctions) {
      this.selectedFunctionList = options.commonFunctions.split(',');
    }

    this.getFirstDealerList();

    if (this.$isWeixin()) {
      uni.setNavigationBarTitle({
        title: this.title
      });
    }
  },

  onShow() {
    this.getFunctions();
  },

  methods: {
    goToShop() {
      location.href = this.shopUrl;
    },

    loadUrl() {
      this.$u.api.getLoadUrl().then(res => {
        const { ResultCode, ResultMessage } = res;

        if (ResultCode > 0) {
          this.showShop = true;
          this.shopUrl = ResultMessage;
        }
      });
    },
    checkModuleApplyIsOk(dealerId, selectType) {
      return new Promise((reslove, reject) => {
        this.$u.api
          .moduleApplyCheck({
            SelectType: selectType,
            DealerId: dealerId
          })
          .then(res => {
            const { ResultCode } = res;
            if (ResultCode === 1) {
              reslove(true);
            }
          });
      });
    },

    onClick() {
      this.$u.api
        .addCommonFunctions({
          CommonFunctionsList: this.selectedFunctionList.map(item => {
            return {
              ObjectId: item
            };
          })
        })
        .then(res => {
          const { ResultCode, ResultMessage } = res;
          if (ResultCode == 1) {
            this.$u.toast(ResultMessage);
            uni.reLaunch({
              url: '/pages/home/home'
            });
          }
        });
    },

    onPickerChange(e, level) {
      let dealerList = [];
      let dealer = {};
      let dealerIndex = -1;
      if (level == 1) {
        dealerList = this.FirstDealerList;
        dealer = this.FirstDealer;
        dealerIndex = this.FirstDealerIndex;
      } else if (level == 2) {
        dealerList = this.DoubleDealerList;
        dealer = this.DoubleDealer;
        dealerIndex = this.DoubleDealerIndex;
      } else if (level == 3) {
        dealerList = this.StoreDealerList;
        dealer = this.StoreDealer;
        dealerIndex = this.StoreDealerIndex;
      }

      if (!e[0].value || !e[0].label) {
        if (dealerList.length > 0) {
          dealer.value = dealerList[0].Key;
          dealer.label = dealerList[0].Value;
        } else {
          return false;
        }
      } else {
        dealer = e[0];
      }

      dealerIndex = dealerList.findIndex(item => item.Key == dealer.value);

      if (level == 1) {
        this.FirstDealer = dealer;
        this.FirstDealerIndex = dealerIndex;
        this.params.FirstDealerId = dealer.value;

        if (this.showApplyStore || this.showApplyDouble) {
          this.initDoubleDealer(dealer);
          this.StoreDealer = {};
          this.StoreDealerIndex = -1;
          this.StoreDealerList = [];
        }
      } else if (level == 2) {
        this.DoubleDealer = dealer;
        this.DoubleDealerIndex = dealerIndex;
        this.params.DoubleDealerId = dealer.value;

        if (this.showApplyStore) {
          this.initStoreDealer(dealer);
        }
      } else if (level == 3) {
        this.StoreDealer = dealer;
        this.StoreDealerIndex = dealerIndex;

        this.params.StoreDealerId = dealer.value;
      }
    },

    resetSearch() {
      this.FirstDealer = {};
      this.FirstDealerIndex = -1;

      this.DoubleDealer = {};
      this.DoubleDealerIndex = -1;
      this.DoubleDealerList = [];

      this.StoreDealer = {};
      this.StoreDealerIndex = -1;
      this.StoreDealerList = [];

      this.params.FirstDealerId = null;
      this.params.DoubleDealerId = null;
      this.params.StoreDealerId = null;
    },

    getFunctions() {
      this.$u.api
        .getCommonFunctions({
          Level: this.level,
          ParentId: this.parentId
        })
        .then(res => {
          console.log(res);
          const { CommonFunctionsList, ResultCode } = res;
          if (ResultCode == 1) {
            CommonFunctionsList.forEach(item => (item.checked = false));

            this.functionList = CommonFunctionsList.filter(item => item.IsShowHide > 0);
            // this.functionList = CommonFunctionsList;

            // if (this.parentId == 3 || this.parentId == 4) {
            // 	this.$u.api
            // 		.permissionQuery({
            // 			type: this.parentId
            // 		})
            // 		.then(res => {

            // 			// 根据ObjectId_str逗号拆分对应显示
            // 			// 1 	渠道调整
            // 			// 2 	信息维护
            // 			// 4	模块样机
            // 			// 6	户外套装
            // 			// 8	奖牌
            // 			// 10	设计申请
            // 			// 12	门店动力金
            // 			// 13	渠道补贴
            // 			// 16	品宣物料申请
            // 			if (res.Count > 0) {
            // 				this.showInformationChange = true;
            // 				this.functionList = CommonFunctionsList;
            // 			}else {
            // 				this.functionList = CommonFunctionsList.filter(item => item.CustomNo != '8')
            // 			}
            // 		});
            // }else {
            // 	this.functionList = CommonFunctionsList;
            // }
          }
        });
    },

    groupChange(e) {
      // this.selectedFunctionList = e.detail.value;
      const selected = e.detail.value;

      console.log(selected);

      this.selectedFunctionList = selected;
    },

    getFirstDealerList() {
      this.$u.api
        .getDealerDic({
          Level: 1
        })
        .then(res => {
          const { ResultCode, DealerList } = res;
          if (ResultCode === 1) {
            this.FirstDealerList = DealerList;
          }
        });
    },

    initDoubleDealer(dealer) {
      this.DoubleDealer = {};
      this.DoubleDealerIndex = -1;
      this.DoubleDealerList = [];
      this.getDoubleDealerList(dealer.value);
    },

    initStoreDealer(dealer) {
      this.StoreDealer = {};
      this.StoreDealerIndex = -1;
      this.StoreDealerList = [];
      this.getStoreDealerList(dealer.value);
    },

    getDoubleDealerList(parentId) {
      this.$u.api
        .getDealerDic({
          Level: 2,
          ParentId: parentId
        })
        .then(res => {
          const { ResultCode, DealerList } = res;
          if (ResultCode === 1) {
            this.DoubleDealerList = DealerList;
          }
        });
    },

    getStoreDealerList(parentId) {
      this.$u.api
        .getDealerDic({
          Level: 3,
          ParentId: parentId
        })
        .then(res => {
          const { ResultCode, DealerList } = res;
          if (ResultCode === 1) {
            this.StoreDealerList = DealerList;
          }
        });
    }
  }
};
</script>

<style>
page {
  background-color: #fafafa;
}
</style>

<style lang="scss">
.grid-text {
  font-size: 13px;
  color: #333;
  margin-top: 5px;
  display: inline-block;
  width: 80px;
  text-align: center;
}

.grid-item {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.bottom-btn {
  position: fixed;
  bottom: 0px;
  left: 0;
  right: 0;
  width: 100%;
  z-index: 99;
  padding-bottom: 40px;
  background-color: #ffffff;
}

.card-grid {
  margin: 0 20px;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-auto-rows: auto;
  gap: 15px 20px;
  margin-top: 20px;

  .card-item {
    background-color: #ffffff;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    border-radius: 8px;
    padding: 15px 0;

    .label {
      margin-top: 5px;
    }
  }
}
</style>
